<template>
	<div>
		<div class="toolbar mt-2">
			<a-form ref="searchRef" layout="inline" :model="searchState" @finish="current=1;expandedRowKeys=[];loading=true;initData()">
				<a-form-item label="名称">
					<a-input v-model:value="searchState.name" placeholder="请输入" allow-clear></a-input>
				</a-form-item>

				<a-form-item>
					<a-space>
						<a-button type="primary" html-type="submit">
							<search-outlined />搜索
						</a-button>

						<a-button v-permission="['admin','flowType:create']" @click="addIndustry">
							<plus-outlined />添加
						</a-button>
					</a-space>
				</a-form-item>
			</a-form>
		</div>

		<div class="container">
			<a-table :columns="columns" :scroll="tableScroll" :expanded-row-keys="expandedRowKeys" row-key="id" :data-source="flowSource" :pagination="pagination" :loading="loading" :row-selection="rowSelection" @change="initData" @expanded-rows-change="expandedRowsChange ">
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'flowTypeNodes'">
						<!-- <a-space> -->
						<div v-for="(item) in record.flowTypeNodes" :key="item.id">
							<!-- <a-tag >{{ item.name }}</a-tag> -->
							{{ item.no }}:
							<a-tag v-for="(itema) in item.roles" :key="itema.id">
								<!-- <a-tag >{{ item.name }}</a-tag> -->
								{{ itema.name }}
							</a-tag>
						</div>

						<!-- </a-space> -->
					</template>
					<template v-if="column.key === 'roles'">
						<!-- <a-space> -->
						<a-tag v-for="(item) in record.roles" :key="item.id">
							<!-- <a-tag >{{ item.name }}</a-tag> -->
							{{ item.name }}
						</a-tag>

						<!-- </a-space> -->
					</template>
					<template v-else-if="column.key === 'operation'">
						<a-space>
							<!-- <a-button
								type="link"
								@click="toDetail(record)"
							>
								详情
							</a-button>-->

							<!-- 							<a-button v-if="!record.category4" type="link" @click="addIndustry(record.id)">
								<plus-outlined />添加审批角色
							</a-button>-->
							<a-button v-permission="['admin','flowType:update']" type="link" @click="editIndustry(record)">
								<edit-outlined />修改
							</a-button>
							<a-button v-permission="['admin','flowType:update']" type="link" style="color:#ff7875" @click="deleteIndustry(record.id)">
								<delete-outlined />删除
							</a-button>
						</a-space>
					</template>
				</template>
			</a-table>

			<a-modal v-model:visible="visible" :width="700" :title="`${formState.key ? '修改' : '添加'}审批流`" @ok="saveIndustry">
				<a-form ref="formRef" :model="formState" v-bind="{labelCol: { style: { width: '170px' } }}">
					<!-- <template> -->
					<!-- <a-form-item
						label="审批节点"
						name="flowTypeNodes"
						:rules="{required:true, message:'请添加审批节点'}"
					>-->

					<a-form-item label="名称" name="name" :rules="{required:true, message:'请输入名称'}">
						<a-input v-model:value="formState.name" />
					</a-form-item>
					<!-- <a-form-item
						label="审批角色"
						name="role_ids"
					>
						<a-tree-select
							v-model:value="formState.role_ids"
							:show-search="true"
							:tree-checkable="false"
							multiple
							:dropdown-style="{}"
							tree-default-expand-all
							:tree-data="roleSource"
							:field-names="{children: 'children',label: 'label',value: 'id'}"
							tree-node-filter-prop="label"
						></a-tree-select>
					</a-form-item>-->
					<!-- 					<a-form-item label="审批人角色" name="approver_role">
						<a-input v-model:value="formState.approver_role" />
					</a-form-item>-->
					<a-form-item label="模块ID" name="module_id" :rules="{required:true, message:'模块id必填唯一索引'}">
						<a-input v-model:value="formState.module_id" />
					</a-form-item>
					<a-form-item label="模块数据表名" name="tb_name" :rules="{required:false, message:'模块数据表名没有可不填'}">
						<a-input v-model:value="formState.tb_name" />
					</a-form-item>
					<a-form-item label="模块数据表字段" name="tb_field" :rules="{required:false, message:'模块表字段没有可不填'}">
						<a-input v-model:value="formState.tb_field" />
					</a-form-item>
					<a-form-item label="数据表主键字段默认id" name="tb_pk" :rules="{required:false, message:'模块数据表字段主键默认id'}">
						<a-input v-model:value="formState.tb_pk" />
					</a-form-item>
					<a-form-item label="模块数据表父表名" name="parent_tb_name" :rules="{required:false, message:'模块数据表父表名没有可不填'}">
						<a-input v-model:value="formState.parent_tb_name" />
					</a-form-item>
					<a-form-item label="模块数据表父表字段" name="parent_tb_field" :rules="{required:false, message:'模块表父表字段没有可不填'}">
						<a-input v-model:value="formState.parent_tb_field" />
					</a-form-item>
					<a-form-item label="数据表外键默认pid(关联父表)" name="tb_foreign_of_parent_tb" :rules="{required:false, message:'模块表父表外键主键字段没有可不填'}">
						<a-input v-model:value="formState.tb_foreign_of_parent_tb" />
					</a-form-item>
					<a-form-item label="模块数据表父表主键默认id" name="parent_tb_pk" :rules="{required:false, message:'模块表父表主键字段没有可不填'}">
						<a-input v-model:value="formState.parent_tb_pk" />
					</a-form-item>
					<a-form-item label="路由地址" name="route_path" :rules="{required:false, message:'路由地址'}">
						<a-input v-model:value="formState.route_path" />
					</a-form-item>
					<a-form-item label="路由名称" name="route_name" :rules="{required:true, message:'路由名称'}">
						<a-input v-model:value="formState.route_name" />
					</a-form-item>
					<a-form-item label="备注" name="remark">
						<a-input v-model:value="formState.remark" />
					</a-form-item>
					<div v-for="item in formState.flowTypeNodes" :key="item.id">
						<a-form-item>
							<template #label>
								<span>审批节点【{{ item.no }}】</span>
								<a-tag @click="delNode(item)">删除</a-tag>
							</template>
							<a-input v-model:value="item.name">
								<template #prefix>名称:</template>
							</a-input>
							<a-input v-model:value="item.number_of_approvers">
								<template #prefix>人数:</template>
							</a-input>
							<a-tree-select v-model:value="item.role_ids" :show-search="true" :tree-checkable="false" multiple :dropdown-style="{}" tree-default-expand-all :tree-data="roleSource" :field-names="{label: 'label', value: 'value'}" tree-node-filter-prop="label"></a-tree-select>
						</a-form-item>
					</div>
					<div style="display: flex;justify-content: center;">
						<a-button @click="addNode">新增审批节点</a-button>
					</div>
				</a-form>
			</a-modal>
		</div>
	</div>
</template>
<script setup>
import { ref, reactive, computed, getCurrentInstance, watch } from "vue";
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import router from "../router";
const { proxy } = getCurrentInstance();

import { post, postJson, treeToList } from "../utils";
import { usePagination } from "vue-request";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const query = route.query;
const roleSource = ref();
post("flow/getRoles").then(data => {
	roleSource.value = data.map(d => {
		//判断是否为公司
		// if (d.value.slice(-2) === "-0") {
		// 	//d.disabled = true;
		// 	//d.disableCheckbox = true;

		// 	//分公司不可选
		// 	d.selectable = false;
		// }
		return d;
	});
});
const searchRef = ref();
const searchState = reactive({});

const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 250
}));

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 60,
		align: "left",
		fixed: "left"
	},
	{
		title: "模块ID",
		dataIndex: "module_id",
		key: "module_id",
		width: 120,
		align: "left"
	},

	{
		title: "数据表名",
		dataIndex: "tb_name",
		key: "tb_name",
		width: 120,
		align: "left"
	},
	{
		title: "数据表字段",
		dataIndex: "tb_field",
		key: "tb_field",
		width: 100,
		align: "left"
	},
	{
		title: "路由名称",
		dataIndex: "route_name",
		key: "route_name",
		width: 120
	},
	{
		title: "路由地址",
		dataIndex: "route_path",
		key: "route_path",
		width: 120
	},
	{
		title: "名称",
		dataIndex: "name",
		sorter: false,
		width: 200,
		ellipsis: true
	},
	{
		title: "审批节点",
		key: "flowTypeNodes",
		sorter: false,
		width: 260,
		resizable: true
		// ellipsis: true
	},
	{
		title: "数据表主键字段默认id",
		dataIndex: "tb_pk",
		width: 120
	},
	{
		title: "模块数据表父表名",
		dataIndex: "parent_tb_name",
		width: 120
	},
	{
		title: "模块数据表父表字段",
		dataIndex: "parent_tb_field",
		width: 120
	},
	{
		title: "数据表外键默认pid(关联父表)",
		dataIndex: "tb_foreign_of_parent_tb",
		width: 120
	},
	{
		title: "模块数据表父表主键默认id",
		dataIndex: "parent_tb_pk",
		width: 120
	},
	// {
	// 	title: "审批角色",
	// 	key: "roles",
	// 	sorter: false,
	// 	width: 240,
	// 	resizable: true,
	// 	// ellipsis: true
	// },
	{
		title: "备注",
		dataIndex: "remark",
		sorter: false,
		width: 360,
		ellipsis: true
	},
	//自动调节表格剩余宽度
	{},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 120,
		align: "center"
	}
];
const addNode = () => {
	var nodes = formState.value.flowTypeNodes || [];
	nodes.push({
		name: "名称",
		no: nodes.length + 1
	});
	formState.value = { ...formState.value, flowTypeNodes: nodes };
	// console.log(formState.value);
};
const delFlowTypeNode = id => {
	post("flow/delFlowTypeNode", { id }).then(e => {
		var nodes = formState.value.flowTypeNodes.filter(item => {
			if (id !== item.id) {
				return item;
			}
		});

		formState.value = { ...formState.value, flowTypeNodes: nodes };
		initData();
	});
};
const delNode = e => {
	delFlowTypeNode(e.id);
	// console.log(idx);
};
const { data, loading, run, current, pageSize, total } = usePagination(params => post("flow/getFlowTypeList", { ...params, ...searchState }), {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const flowSource = computed(() => data.value?.data || []);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.name) searchState.name = query.name;
	// router.replace({ query: {}})
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

watch(flowSource, value => {
	const { name } = searchState;
	if (name) expandedRowKeys.value = treeToList(JSON.parse(JSON.stringify(value))).map(d => d.id);

	//删除记录后返回上一页
	if (value.length === 0 && current.value > 1) current.value--;
});

const expandedRowKeys = ref([]);
const expandedRowsChange = e => {
	expandedRowKeys.value = e;
};

const rowSelection = ref();

const visible = ref(false);

const formRef = ref();
const formState = ref({});

const toDetail = row => {
	// router.push({ name: "flowDetail", params: { id: rowid } });
	router.push({
		name: "flow",
		params: { type_id: row.id }
	});
	// formState.value = {
	// 	parent_id: parseInt(parentId) || 0
	// };
	// visible.value = true;
};
const addIndustry = parentId => {
	formRef.value?.clearValidate();
	formState.value = {
		flowTypeNodes: []
		// role_ids: [],
	};
	visible.value = true;
};
const editIndustry = record => {
	formRef.value?.clearValidate();

	visible.value = true;
	const data = { ...record };

	// data.role_ids = record.roles.map((d) => d.id);
	var nodes = record.flowTypeNodes.map(d => d.id);
	// nodes.push({
	// 	name: "名称",
	// 	no: nodes.length + 1,
	// });

	//data.flowTypeNodes是响应式数据，从api获取的是字符型，第一次调用editIndustry后会格式化为数组，第二次在调用已经是数组了，此时再调用split会报错

	data.flowTypeNodes.map(e => {
		e.role_ids = e.roles.map(d => d.id);
		//if (typeof e.role_ids === "string") e.role_ids = e.role_ids?.split(",").map(d => parseInt(d)) || [];
	});
	// formState.value = data;
	// formState.value = { ...record };
	formState.value = data;
};
const saveIndustry = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };
			// if (params.birthday)
			// 	params.birthday = params.birthday.format("YYYY-MM-DD");
			// params.role_ids = params.role_ids.join(",");

			params.flowTypeNodes = params.flowTypeNodes.map(d => {
				d.role_ids = d.role_ids?.join(",");
				return d;
			});

			postJson("flow/saveFlowType", params)
				.then(() => {
					proxy.$message.success("提交成功", 1);
					visible.value = false;

					// expandedRowKeys.value.push(params.parent_id);

					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {
			//console.log(err);
		});
};
const deleteIndustry = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的行业吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("flow/deleteFlowType", { id }).then(() => {
				proxy.$message.success("行业删除成功");

				initData();
			});
		}
	});
};

watch(visible, value => {
	if (value) formRef.value?.clearValidate();
});
</script>

<style scoped>
.toolbar {
	padding: 12px;
	background: #fff;
}

.container {
	background: #fff;
	padding: 12px;
}
</style>